package com.gs.wzweather.service.impl;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gs.wzweather.dao.SiteDao;
import com.gs.wzweather.bo.ForeHourTypeToken;
import com.gs.wzweather.bo.ForeDayTypeToken;
import com.gs.wzweather.bo.Response;
import com.gs.wzweather.entity.Site;
import com.gs.wzweather.service.SiteService;
import com.gs.wzweather.utils.Constant;
import com.gs.wzweather.utils.HttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SiteServiceImpl implements SiteService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    Gson gson = new Gson();

    @Autowired
    SiteDao siteDao;

    @Override
    public Response getSite() {
        List<Site> sites = siteDao.queryAll();
        for (int i = 0; i < sites.size(); i++) {
            Site site = sites.get(i);
            String id = site.getStationId();
            getFore24h(id);
        }
        return null;
    }

    /*
    winds：风速
    windd：风向
    ww1：1小时天气现象
    t：温度
    pr01：1小时降水量
 */
    public void getFore24h(String staId) {
        String element = "winds,windd,ww1,t,pr01";
        String url = Constant.Url.FORE_24_HOUR + Constant.Url.PARAM_STAID + staId + Constant.Url.PARAM_ELEMENT + element;
        try {
            String result = HttpUtils.request(url);
            //  logger.info("getFore24h->{}", result);
            ForeHourTypeToken fore24hList = gson.fromJson(result, new TypeToken<ForeHourTypeToken>() {
            }.getType());
            if (fore24hList.getReturnCode() == 0) {
                logger.info("getFore24h->{}", staId);
            }
        } catch (Exception e) {
            logger.info("getFore24h->{}", e.getMessage());
        }
    }

    /*
        winds：风速
        windd：风向
        pr24：24小时降水量
        t：温度
     */
    public void getFore7d(String staId) {
        String element = "winds,windd,t,pr24";
        try {
            String result = HttpUtils.request(Constant.Url.FORE_7_DAY + Constant.Url.PARAM_STAID + staId + Constant.Url.PARAM_ELEMENT + element);
            //   logger.info("getFore7d->{}", result);
            ForeDayTypeToken fore7dList = gson.fromJson(result, new TypeToken<ForeDayTypeToken>() {
            }.getType());
            if (fore7dList.getReturnCode() == 0) {
                logger.info("getFore7d->{}", staId);
            }
        } catch (Exception e) {
            logger.info("getFore7d->{}", e.getMessage());
        }
    }
}
